import React, {useState} from 'react';
import './SDK.less';

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faSliders, faLightbulb, faSun, faFingerprint} from '@fortawesome/free-solid-svg-icons'
// 引入组件库的css
import 'qcloud-iot-panel-component/lib/index.css';
import { BoolWidget } from 'qcloud-iot-panel-component';
import { NumberInput } from 'qcloud-iot-panel-component';
import { EnumSlider } from 'qcloud-iot-panel-component';
import { DisplayPanel } from 'qcloud-iot-panel-component';

/*
import { FontAwesomeIcon } from '@fortawesome/fontawesome-free';
import { faCoffee } from '@fortawesome/fontawesome-free';
*/
const sdk = window.h5PanelSdk;

class Light_control_form extends React.Component {

  constructor(props) {
    super(props);
    this.state = {level: 0};
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {    this.setState({level: event});  }
  handleSubmit(event) {
    //alert('亮度等级修改为: ' + this.state.level);
    sdk.controlDeviceData({level:this.state.level});
    event.preventDefault();
  }

  render() {
    return (
        <NumberInput className="light_level_input" value={0} step={10} min={0} max={100} 
        templateInfo={{name: '亮度等级'}} onChange={this.handleChange}/>
    );
  }
}

class SwitchButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: false};
    // 为了在回调中使用 `this`，这个绑定是必不可少的
    this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
      this.setState(state => ({      isToggleOn: !state.isToggleOn    }));
      let toggle = this.state.isToggleOn;
      sdk.controlDeviceData({ai_switch:toggle ? 1 : 0});
    }
    render() {
      if (this.state.isToggleOn)
      {
    return (
          <button className="off_bt" onClick={this.handleClick}> 'AI 关闭'</button>
    );
      }
      else
      {
    return (
          <button className="on_bt" onClick={this.handleClick}> 'AI 开启'</button>
    );
      }
  }
}

class Controler_msg_show_dyn extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      msg_value: "0",
      msg_media: "null",
    };
  }

  async redgetDeviceData () {
    const data = await sdk.getDeviceData();
    const str_data = JSON.stringify(data, null, 2);
    this.setState({msg_media:str_data});
  }

  tick() {
    this.redgetDeviceData();
    if (null == this.state.msg_media)
      return;

    let device_data = this.state.msg_media;
    let device_data_json = JSON.parse(device_data);
    if (null == device_data_json.light)
      return;
    let illum_target = device_data_json.light.Value;
    let illum_value = JSON.stringify(illum_target, null, 2);
    this.setState({msg_value:illum_value});
  }

  componentDidMount() {
    /* 保存定时器 ID */
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    /* 卸载定时器 */
    clearInterval(this.interval);
  }

  render() {
    return (
          <DisplayPanel
            className="panel_display_sets"
            value={this.state.msg_value}
            name={this.props.msg_title}
          />
    );
  }
}

class State_msg_show_dyn extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      msg_value: "0",
      msg_media: "null",
    };
  }

  async redputDeviceData (value_str) {
      sdk.controlDeviceData({time:value_str});
  }

  tick() {
    let time_now = new Date().toLocaleTimeString();
    let time4put = time_now.substr(0,5);
    this.setState({msg_value:time4put});
    this.redputDeviceData(time4put);
    //sdk.tips.alert('time' + time4put);
  }

  componentDidMount() {
    /* 保存定时器 ID */
    this.interval = setInterval(() => this.tick(), 5000);
  }

  componentWillUnmount() {
    /* 卸载定时器 */
    clearInterval(this.interval);
  }
  render() {
    return null
  }
}

class Controler_msg_show extends React.Component {
  render() {
    return (
      <div>
        {this.props.msg_title} : {this.msg_value}
      </div>
    );
  }
}

export default function API() {
  const showDeviceDetail = async () => {
    const isConfirm = await sdk.tips.confirm('是否展示H5设备详情？');

    if (isConfirm) {
      await sdk.tips.alert('当前选择H5设备详情');

      sdk.showDeviceDetail({
        labelWidth: 120,
        marginTop: 8,
        shareParams: {
          a: 'a',
          b: 'b',
        },
        extendItems: [
          {
            labelIcon: 'https://main.qcloudimg.com/raw/be1d876d55ec2479d384e17c94df0e69.svg',
            label: '自定义菜单',
            content: '自定义菜单内容（可选）',
            onClick: () => console.log('点击自定义菜单'),
          },
        ],
        extendButtons: [
          {
            text: '自定义按钮',
            type: 'warning',
            onClick: () => console.log('点击自定义按钮'),
          },
          {
            text: '获取自定义分享参数',
            onClick: async () => {
              const shareParams = await sdk.getShareParams();
              console.log('自定义分享参数: ', shareParams);
            }
          },
          {
            text: '关闭设备详情',
            type: '',
            onClick: () => sdk.hideDeviceDetail(),
          },
        ],
      });
    } else {
      await sdk.tips.alert('当前选择原生设备详情');

      sdk.goDeviceDetailPage();
    }
  };

  const getDeviceStatus = async () => {
    const status = await sdk.getDeviceStatus();
    sdk.tips.alert(`设备在线状态： ${status ? '在线' : '已离线'}`);
  }

  const getDeviceData = async () => {
    const data = await sdk.getDeviceData();
    sdk.tips.alert(`物模型数据：${JSON.stringify(data, null, 2)}`);
    return (data)
  }

  const switch_work_mode = async () => {
    const ans = await sdk.controlDeviceData({mode:1});
    sdk.tips.alert(`模式修改成功`);
  }

  const switch_play_mode = async () => {
    const ans = await sdk.controlDeviceData({mode:2});
    sdk.tips.alert(`模式修改成功`);
  }

  const switch_movie_mode = async () => {
    const ans = await sdk.controlDeviceData({mode:3});
    sdk.tips.alert(`模式修改成功`);
  }

  const switch_learn_mode = async () => {
    const ans = await sdk.controlDeviceData({mode:4});
    sdk.tips.alert(`模式修改成功`);
  }


  const getDeviceIlluma = async () => {
    const data = await sdk.getDeviceData();
    sdk.tips.alert(`获取光照度值：${JSON.stringify(data, null, 2)}`);
  }

  var all_lamp_level = 0;
  const do_control_all = (level) => {
    all_lamp_level = level;
    //alert('亮度等级修改为: ' + all_lamp_level);
  }

  const control_all_lamp = async () => {
    sdk.tips.alert('整体控制所有灯具' + all_lamp_level);
    sdk.controlDeviceData({level:all_lamp_level});
  }

  const do_switch_mode = async () => {
    const ans = await sdk.controlDeviceData({mode:enumVal});
    sdk.tips.alert('切换为' + enumList[enumVal - 1].text + '模式');
  }

const [enumVal, setEnumVal] = useState(1);
const enumList = [
  {text: '工作', value: 1},
  {text: '休闲', value: 2},
  {text: '影院', value: 3},
  {text: '学习', value: 4},
];

  const do_ai_switch= (ai) => {
    console.log(ai);
    //setTitle(ai ? 'AI 开启' : 'AI 关闭')
    sdk.controlDeviceData({ai_switch:ai ? 1 : 0});
  }

  return (
    <div className="sdk">
      <h3><FontAwesomeIcon icon={faSliders} /> 模式选择</h3>

      <div className="control_box">
  <EnumSlider
    icon={'camera'}
    value={enumVal}
    enumList={enumList}
    onChange={(v) => {setEnumVal(v)} }
  />
    <button className="button_box" onClick={do_switch_mode}> <FontAwesomeIcon icon={faFingerprint}/> 确认 </button>
          </div>
      <h3> <FontAwesomeIcon icon={faLightbulb} /> 灯具控制</h3>
      <div className="control_box">
      <NumberInput value={0} step={10} min={0} max={100}  templateInfo={{name: '亮度等级'}} onChange={do_control_all}/>
        <button onClick={control_all_lamp}> <FontAwesomeIcon icon={faFingerprint}/> 确认 </button>
      </div>
        <div>
          <BoolWidget switchColor="1193046" title={'AI Smart'} icon={'camera'} onChange={do_ai_switch}/>
        </div>

      <h3><FontAwesomeIcon icon={faSun} /> 照度值</h3>
      <Controler_msg_show_dyn/>
      <State_msg_show_dyn/>
    </div>
  )
}
